package com.zg.mock.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.zg.mock.domain.dto.DetailBackDTO;
import com.zg.mock.domain.dto.DetailDTO;
import com.zg.mock.domain.dto.InvoiceBackDTO;
import com.zg.mock.domain.dto.InvoiceDTO;
import com.zg.mock.service.InvoiceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.tomcat.jni.Time;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/19 10:22
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class InvoiceServiceImpl implements InvoiceService {

    private final RestTemplate restTemplate;


    @Override
    public InvoiceBackDTO accept(InvoiceDTO invoiceDTO) {
        InvoiceBackDTO invoiceBackDTO = convert(invoiceDTO);
        String apiUrl = invoiceDTO.getBizCallbackUrl();

        List<DetailBackDTO> invoiceBackDTOList = Lists.newArrayList();
        List<DetailDTO> detailDTOList = invoiceDTO.getDetail();
        for (int i = 0; i < detailDTOList.size(); i++) {
            DetailDTO detailDTO = detailDTOList.get(i);
            DetailBackDTO detailBackDTO = convertDetail(detailDTO);
            invoiceBackDTOList.add(detailBackDTO);
        }
        invoiceBackDTO.setDetail(invoiceBackDTOList);
        log.info("发票回调参数：{}", invoiceBackDTO);
        return invoiceBackDTO; 
    }

    @Async
    public void asyncMethod(InvoiceDTO invoiceDTO,InvoiceBackDTO invoiceBackDTO) {

        String apiUrl = invoiceDTO.getBizCallbackUrl();
        try {
            Thread.sleep(5000);

            log.info("延迟5秒后继续执行");
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, invoiceBackDTO, String.class);
            log.info("响应结果：{}", response.getBody());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }


    /**
     * 将 InvoiceDTO 转换为 InvoiceBackDTO
     */
    public static InvoiceBackDTO convert(InvoiceDTO dto) {
        if (dto == null) return null;
        InvoiceBackDTO backDTO = new InvoiceBackDTO();
        // 直接赋值字段（字段名和类型完全一致）
        BeanUtil.copyProperties(dto, backDTO);
        // 模拟未匹配字段
        simulateMissingFields(backDTO);

        return backDTO;
    }

    /**
     * 转换 DetailDTO → DetailBackDTO
     */
    private static DetailBackDTO convertDetail(DetailDTO detail) {
        if (detail == null) return null;

        DetailBackDTO dto = new DetailBackDTO();
        dto.setDetailIndex(detail.getDetailIndex());
        dto.setDetailType(detail.getDetailType());
        dto.setCommodityCode(detail.getCommodityCode());
        dto.setGoodsName(detail.getGoodsName());
        dto.setWithTaxFlag(detail.getWithTaxFlag());
        dto.setGoodsPrice(detail.getGoodsPrice());
        dto.setTaxFreePrice(detail.getTaxFreePrice());
        dto.setGoodsNum(detail.getGoodsNum());
        dto.setTaxrate(detail.getTaxrate());
        dto.setSpecType(detail.getSpecType());
        dto.setGoodsUnit(detail.getGoodsUnit());
        dto.setGoodsCode(detail.getGoodsCode());
        dto.setSelfCode(detail.getSelfCode());
        dto.setFavouredPolicyFlag(detail.getFavouredPolicyFlag());
        dto.setFavouredPolicyName(detail.getFavouredPolicyName());
        dto.setFavouredPolicyCode(detail.getFavouredPolicyCode());
        dto.setMtzl(detail.getMtzl());

        // 模拟 DetailBackDTO 特有字段
        dto.setZeroRateFlag(0);
        dto.setDeduction(0);
        dto.setTaxFreeAmount(0.0);
        dto.setGoodsCodeAbb("商品简称");
        dto.setColumnFirst("模拟列1");
        dto.setColumnSecond("模拟列2");
        dto.setColumnThree("模拟列3");
        dto.setColumnFour("模拟列4");
        dto.setColumnFive("模拟列5");

        return dto;
    }

    /**
     * 模拟 InvoiceBackDTO 特有字段
     */
    private static void simulateMissingFields(InvoiceBackDTO dto) {
        Date now = new Date();
        String uuid = UUID.randomUUID().toString();

        if (dto.getInvoiceNumber() == null) {
            dto.setInvoiceNumber("INVOICE_" + new Date().getTime());
        }

        dto.setInvoiceId(uuid);
        dto.setQrCode("01,31,,25142000000036872184,29613406.81,20250516,,5E33");

        // 时间字段（InvoiceDTO 仅有 orderDate/deliverDate）
//        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
//        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));


        dto.setCreateTime(DateUtil.formatDateTime(new Date()));
        dto.setInvoiceTime(DateUtil.formatDateTime(new Date()));
        dto.setUpdateTime(DateUtil.formatDateTime(new Date()));

        // 状态字段
        dto.setSuccessFlag(true);
        dto.setInvoiceStatus(1);
        dto.setErrorMessage(null);

        // 文件 URL
        dto.setPdfUrl("https://inv.jss.com.cn/fp2/mkgt7tXwhoueWcSKa5C5XDrp_r_EGjE2UqWJEUOINX1GJvHHRBIXgvyoCye7GfkwDOAJtMPEulmy7ZiLFkTlMw.pdf");
        dto.setImageUrl("https://inv.jss.com.cn/fp2/mkgt7tXwhoueWcSKa5C5XLiYOL82SVNnSjuVDQ2zC1FVzi713FufKrFRRJ1cFwTvbbl3y3BzUNAerMWpvCv3Cg.jpg,https://inv.jss.com.cn/fp2/mkgt7tXwhoueWcSKa5C5XLvLGyf8csrwaUW0YwdUOh536YhwfgEH_MnqGhmprQ2wn_dPrRWLyVCM4epkxfwlLw.jpg");
        dto.setOfdUrl("https://inv.jss.com.cn/fp2/mkgt7tXwhoueWcSKa5C5XIbgz122w9x0i8RfixIEYGulaFOSPf7zhSI9BM0GRDoKfffpxJPHFsI65cc77Dx4TQ.ofd");

        // 金额字段
        dto.setTaxFreeAmountTotal(Double.parseDouble("26206554.70"));
        dto.setTaxTotal(Double.parseDouble("3406852.11"));
        dto.setTaxAmountTotal(Double.parseDouble("29613406.81"));

        // 扩展字段
        dto.setRedReason(null);
        dto.setXmlUrl(null);
        dto.setCompensateId(null);
        dto.setMtrl(null);
        dto.setMtql(null);
        dto.setMthf(null);
        dto.setInvoiceStatus(1);

    }


}
